<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>植物大战僵尸</title>
    <style>
        #container{
            width: 950px;
            overflow: hidden;/*溢出隐藏 */
            position: relative;
        }
        #bg{
            margin-left: -100px;/*向左移动100像素*/
        }
        .card{
            z-index: 10;/*数值越大，在上层显示*/
            position: absolute;
            top: 0;
            left: 0;
        }
        .font{
            z-index: 20;
            position: absolute;
            top: 40px;
            left: 68px;
            color: red;
        }
        #score{
            position: absolute;
            top: 65px;
            left: 53px;
            font-size: 20px;
            color: black;
            z-index: 20;
        }
        .button{
            position: absolute;
            z-index: 35;
            top: 0px;
            left: 860px;
            width: 80px;
            height: 40px;
        }
		

    </style>
    <script src="sprites.js"></script>
</head>
<body ondragstart="return false">
    <div id="container">
        <img id="bg" src="images/Background.jpg">
        <img class="card" onclick="dragPeashooter(1)" src="images/Peashooter.png">
        <img class="card" onclick="dragPeashooter(2)" src="images/SnowPea.png" style="left: 100px;" >
        <img class="card" onclick="dragPeashooter(3)" src="images/SunFlower.png" style="left: 200px;" >
        <img class="card" onclick="dragPeashooter(4)" src="images/Repeater.png" style="left: 300px;">
        <img class="card" onclick="dragBomb(5)" src="images/Jalapeno.png" style="left: 400px;">
        <img class="card" onclick="dragPeashooter(6)" src="images/GatlingPea.png" style="left: 500px">
        <img class="card" onclick="dragPeashooter(7)" src="images/WallNut.png" style="left: 600px;">
        <img class="card" src="images/ShovelBack.png" style="left: 780px;">
        <img class="card" onclick="dragShovel(0)" src="images/Shovel.png" style="left: 780px;z-index: 15">
        <img class="card" style="top: 60px;" src="images/SunBack.png">
		
		<audio id="myAudio1" src="bgm.m4a" loop = 'true'></audio>
		<audio id="myAudio2" src="win.mp3" loop = "false"></audio>
		<audio id="myAudio3" src="lose.mp3" loop = "false"></audio>
        <div class="font">100</div>
        <div class="font" style="left: 168px;">175</div>
        <div class="font" style="left: 268px;">50</div>
        <div class="font" style="left: 368px;">200</div>
        <div class="font" style="left: 468px;">100</div>
        <div class="font" style="left: 568px;">450</div>
        <div class="font" style="left: 668px;">50</div>

        <div id="score">99999</div>
        <img class="button" onclick="window.location.reload()" src="images/Button.png"></img>
    </div>
    <script src="sprites.js"></script>
    <script>
        var counter = 0;//全局计数器
        var duration = 1000;
        var zbIndex = 0;//僵尸数组下表
        var zombies = [];//僵尸数组
        var shooter = [];//植物数组
        var bullets = [];
		let lawnmowers = [];
        var zbDieNo = 0;//打死的个数
        var suns = [];//太阳数组
        var grass = [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]
        var statement = false;//植物是否种下
        var statement_chan = false;
        var div = document.getElementById('score');
		var audio1 = document.getElementById("myAudio1"); // 获取 <audio> 元素
		var audio2 = document.getElementById("myAudio2"); // 获取 <audio> 元素
		var audio3 = document.getElementById("myAudio3"); // 获取 <audio> 元素
        //主函数
        window.onload = function (){
            //var zombie = createZombie(0);
			
			 
			// 设置音量
			audio1.volume = 0.7;
			 
			// 开始播放音乐
			audio1.play();
			 
			// 暂停音乐
			// audio.pause();
			 
			// 跳转到特定时间点
			// audio.currentTime = 120; // 将当前时间设为120秒
			 
			// 判断音乐是否正在播放
			if (audio1.paused) {
			    console.log('音乐已经暂停');
			} else {
			    console.log('音乐正在播放');
			}
			
			lawnmowers.push(createLawnMower(0));
			lawnmowers.push(createLawnMower(1));
			lawnmowers.push(createLawnMower(2));
			lawnmowers.push(createLawnMower(3));
			lawnmowers.push(createLawnMower(4));
            setInterval(()=>{
                addSprites();
                spriteStep();
                onHitting();
            },100/8);//每隔125ms就会重绘
        }
        //消耗太阳
        function score(score){
            if (score < 0 && parseInt(div.innerHTML) < Math.abs(score)){
                return false;
            }
            div.innerHTML = parseInt(div.innerHTML) + score;
            return true;
        }

        //植物射击
        function shoot(peashooter){
            if (peashooter.type == 3){//无论有无僵尸，均产生(向日葵)
                suns.push(createSun(peashooter,suns.length,sun=>{
                    suns = suns.filter(item=>item.code != sun.code);
                    container.removeChild(sun);
                    score(10000);
                }));
            }else {//射手根据有没有僵尸
                for (var zombie of zombies){
                    if (zombie.route == peashooter.route
                        && zombie.offsetLeft > peashooter.offsetLeft-50){
                        bullets.push(createBullet(peashooter,bullets.length,bullet=>{
                            bullets = bullets.filter(item=>item.code!=bullet.code);
                            container.removeChild(bullet);
                        }));
                        break;
                    }
                }
            }

        }

        //辣椒爆炸函数碰撞
        function boom(peashooter){
                for (var zombie of zombies){
                    if (peashooter.route == zombie.route){
                        zombie.src = 'images/BoomDie.gif';
                        zombieDie(zombie);
                    }
                }
        }
        //点击卡片会调用铲子功能
        function dragShovel(type){
            statement_chan = false;
            createShovel(type,shovel=>{
                shovel.src = 'images/Shovel.png';
                shanchuBy(shovel);
                console.log(shovel);
                grass[shovel.route][shovel.columns] = 0;
                container.removeChild(shovel);//爆炸后删除
            });
        }

        //点击卡片会调用爆炸drag
        function dragBomb(type){
            statement = false;
            createBomb(type,bomb=>{
                //种进地里，减太阳
                var result = score(-bomb.score);
                if (!result){
                    grass[bomb.route][bomb.columns] = 0;
                    container.removeChild(bomb);
                    return;
                }
                if (type == 5){
                    bomb.src = 'images/Jalapeno.gif';
                    setTimeout(()=>{
                        bomb.style.left = '160px';
                        bomb.style.top = bomb.offsetTop - 40 +'px';
                        bomb.src = 'images/JalapenoAttack.gif';
                        boom(bomb);
                    },700);
                    setTimeout(()=>{
                        grass[bomb.route][bomb.columns] = 0;
                        container.removeChild(bomb);//爆炸后删除
                    },1700)
                }

            });
        }

        //点击卡片会调用射手drag
        function dragPeashooter(type){
            statement = false;
            createPeashooter(type,peashooter=>{
                //种进地里，减太阳
                var result = score(-peashooter.score);

                if (!result){
                    grass[peashooter.route][peashooter.columns] = 0;
                    container.removeChild(peashooter);
                    return;
                }

                peashooter.timer = setInterval(()=>{
                    shoot(peashooter);
                },type == 3?100:10);//向日葵太阳与子弹产生速度
                if (type == 4){
                    setTimeout(()=>{
                        peashooter.timer2 = setInterval(()=>{
                            shoot(peashooter);
                        },2000);
                        shoot(peashooter);
                    },100);
                }
                if (type == 6){
                    setTimeout(()=>{
                        peashooter.timer3 = setInterval(()=>{
                            shoot(peashooter);
                        },2000);
                        shoot(peashooter);
                    },100);
                    setTimeout(()=>{
                        peashooter.timer4 = setInterval(()=>{
                            shoot(peashooter);
                        },2000);
                        shoot(peashooter);
                    },200);
                    setTimeout(()=>{
                        peashooter.timer5 = setInterval(()=>{
                            shoot(peashooter);
                        },2000);
                        shoot(peashooter);
                    },300);
                }
                shoot(peashooter);
                shooter.push(peashooter)

            });
        }


        //生产僵尸精灵
        function addSprites(){
            var zombiesWonbg1 = document.createElement('img');
            var zombiesWonbg2 = document.createElement('img');
            if (zbIndex> 20){
                counter = 0;//大于20，不再生产
                return;
            }
            counter++;
            if (parseInt(counter/duration) >= zbIndex){
                zombies.push(createZombie(zbIndex,()=>{
					
                    zombiesWonbg1.src = 'images/ZombiesWon.png';
                    zombiesWonbg1.style.position = 'absolute';
                    zombiesWonbg1.style.zIndex = 30;
                    zombiesWonbg1.style.top = 100+'px';
                    zombiesWonbg1.style.left = 230+'px';
                    container.appendChild(zombiesWonbg1);
                    zombiesWonbg2.src = 'images/over.png';
                    zombiesWonbg2.style.position = 'absolute';
                    zombiesWonbg2.style.zIndex = 29;
                    zombiesWonbg2.style.top = 0+'px';
                    zombiesWonbg2.style.left = 0+'px';
                    container.appendChild(zombiesWonbg2);
					audio1.pause();
					audio3.play();
					if (!audio3.paused) {
						setTimeout(()=>{
							window.location.reload();
						},5000);
					}
					
                }));
                //两大波僵尸
                if (zbIndex == 2){
                    duration = 100;//密集度变高
                    counter = duration * zbIndex;
                }
                if (zbIndex == 10){
                    duration = 2000;//密集度变低
                    counter = duration * zbIndex;
                }
                if (zbIndex == 11){
                    duration = 100;//密集度变高
                    counter = duration * zbIndex;
                }
                zbIndex++;
            }


        }

        //精灵走步
        function spriteStep() {
            for (var zombie of zombies) {
                zombie.step();//僵尸走
            }
            for (let bullet of bullets) {
                bullet.step();//子弹走
            }
            for (var sun of suns){
                sun.step();//太阳飞
            }
        }

        //僵尸死亡
        function zombieDie(zombie){
            setTimeout(()=>{
                try{
                    zombies = zombies.filter(item=>item.id != zombie.id);//删除数组的中死掉的僵尸
                    container.removeChild(zombie);
                    zbDieNo++;
					// 赢
                    if (zbDieNo > 20){

                        var trophy = document.createElement('img');
                        trophy.src = 'images/trophy.png';
                        trophy.style.position = 'absolute';
                        trophy.style.zIndex = 30;
                        trophy.style.top = 200+'px';
                        trophy.style.left = 400+'px';
						audio1.pause();
						audio2.play();
                        container.appendChild(trophy);
						setTimeout(()=>{
							audio2.pause();
						},5000);
                    }
                }catch (e){}
            },2500);
        }

        //击打僵尸
        function hitZombie(bullet){
            for (var zombie of zombies){
                if (bullet.offsetLeft - 70 > zombie.offsetLeft &&
                    bullet.offsetLeft - 140< zombie.offsetLeft &&
                    bullet.route == zombie.route){
                    zombie.blood--;//僵尸掉血
                    if (bullet.type == 2){//冰冻子弹
                        zombie.speed = 1;
                    }
                    if (zombie.blood == 9){
                        zombie.src = zombie.src.endsWith('Zombie.gif') ?
                            'images/Zombie.gif' : 'images/ZombieAttack.gif';//吃的时候帽子掉
                    }
                    if (zombie.blood == 0){
                        //掉脑袋
                        var head = createHead(zombie);
                        zombie.src = zombie.src.endsWith('Zombie.gif') ?
                            'images/ZombieLostHead.gif' : 'images/ZombieLostHeadAttack.gif';
                        setTimeout(()=>{
                            zombie.src = 'images/ZombieDie.gif';
                            container.removeChild(head);
                        },1000);
                        zombieDie(zombie);
                    }else {
                        zombie.style.opacity = 0.7;
                        setTimeout(()=>{
                            zombie.style.opacity = 1;
                        },100);
                    }
                    return true;
                }
            }
            return false;
        }
		//小推车击杀僵尸
		function lawnmowerShoot(lawnmower) {
			for (let zombie of zombies) {
				if (lawnmower.offsetLeft + 6 > zombie.offsetLeft && lawnmower.route == zombie.route) {
					var head = createHead(zombie);
					zombies = zombies.filter(item=>item.id != zombie.id);//删除数组的中死掉的僵尸
					setTimeout(()=>{
						container.removeChild(head);
					},1000);
					container.removeChild(zombie);
					zbDieNo++;
					if (zbDieNo > 20){
					    var trophy = document.createElement('img');
					    trophy.src = 'images/trophy.png';
					    trophy.style.position = 'absolute';
					    trophy.style.zIndex = 30;
					    trophy.style.top = 200+'px';
					    trophy.style.left = 400+'px';
						audio1.pause();
						audio2.play();
					    container.appendChild(trophy);
						setTimeout(()=>{
							audio2.pause();
						},5000);
					}
				}
			}
		}
		
        //精灵碰撞
        function onHitting() {
            for (var bullet of bullets){
                if (hitZombie(bullet)){
                    bullet.src = 'images/BulletHit.gif';
                }
            }
			for (let lawnmower of lawnmowers) {
				if (lawnmower.speed) {
					lawnmower.step();
					lawnmowerShoot(lawnmower);
				}
			}
            for (var zombie of zombies){
				if (zombie.offsetLeft < 50) {
					for (let lawnmower of lawnmowers) {
						if (zombie.route == lawnmower.route) {
							lawnmower.speed = 4;
							// lawnmowerShoot(lawnmower);
						}
					}
				}
                var peashooter = eatPlantBy(zombie);
                if (peashooter && zombie.src.endsWith('Zombie.gif')){
                    if (zombie.blood <=9){
                        zombie.src = 'images/ZombieAttack.gif';
                    }else if (zombie.status == 5){//铁桶僵尸
                        zombie.src = 'images/BucketheadZombieAttack.gif';
                    }else {//路障僵尸
                        zombie.src = 'images/ConeheadZombieAttack.gif';
                    }
                    peashooter.attack.push(zombie.id);
                    console.log(peashooter.attack);
                }else if(peashooter){
                    if (peashooter.type == 7 && peashooter.blood==1200){
                        peashooter.src = 'images/Wallnut_cracked1.gif';
                    }
                    if (peashooter.type == 7 && peashooter.blood==800){
                        peashooter.src = 'images/Wallnut_cracked2.gif';
                    }
                    if (peashooter.blood == 0){
                        if (peashooter.timer) clearInterval(peashooter.timer);
                        if (peashooter.timer2) clearInterval(peashooter.timer2);
                        if (peashooter.timer3) clearInterval(peashooter.timer3);
                        if (peashooter.timer4) clearInterval(peashooter.timer4);
                        if (peashooter.timer5) clearInterval(peashooter.timer5);

                        shooter.splice(peashooter.index,1);
                        grass[peashooter.route][peashooter.columns] = 0;
                        container.removeChild(peashooter);
                        //吃完继续走
                        for (var id of peashooter.attack){
                            var zz = document.getElementById(id);
                            console.log(zz);
                            if (zz!=null){
                                if ((zz && zz.blood <= 9)){
                                    zz.src = 'images/Zombie.gif';
                                }else if (zz && zz.status == 5){
                                    zz.src = 'images/BucketheadZombie.gif'
                                }else {
                                    zz.src = 'images/ConeheadZombie.gif'
                                }
                            }
                        }
                    }

                }
                if (peashooter && peashooter.blood != 0){
                    peashooter.blood--;
                }
            }
        }


        //删除植物
        function shanchuBy(shovel) {
            len = shooter.length;
            for (var i=0;i<len;i++) {
                var plant = shooter[i];
                if (plant.route == shovel.route && plant.columns == shovel.columns){
                    if (shooter[i].timer) clearInterval(shooter[i].timer);
                    if (shooter[i].timer2) clearInterval(shooter[i].timer2);
                    if (shooter[i].timer3) clearInterval(shooter[i].timer3);
                    if (shooter[i].timer4) clearInterval(shooter[i].timer4);
                    if (shooter[i].timer5) clearInterval(shooter[i].timer5);
                    //单独处理正在吃植物的僵尸
                    for (var zombie of zombies){
                        if (plant.offsetLeft - 40 > zombie.offsetLeft &&
                            plant.offsetLeft - 100< zombie.offsetLeft &&
                            plant.route == zombie.route) {
                            if ((zombie && zombie.blood <= 9)){
                                zombie.src = 'images/Zombie.gif';
                            }else if (zombie && zombie.status == 5){
                                zombie.src = 'images/BucketheadZombie.gif'
                            }else {
                                zombie.src = 'images/ConeheadZombie.gif'
                            }
                        }
                    }

                    grass[shovel.route][shovel.columns] = 0;
                    shooter = shooter.filter(item=>item!=plant);
                    container.removeChild(plant);
                    i=0;
                    len--;
                }
            }
            return null;
        }


        //哪个僵尸吃植物
        function eatPlantBy(zombie){
            for (var i in shooter){
                var peashooter = shooter[i];
                if (peashooter.offsetLeft - 40 > zombie.offsetLeft &&
                    peashooter.offsetLeft - 100< zombie.offsetLeft &&
                    peashooter.route == zombie.route){
                    peashooter.index = i;
                    return peashooter;
                }
            }
            return null;
        }
    </script>
</body>
</html>